<template>
	<view class="page-container">
		<!-- 客户信息 -->
		<view class="section customer">
			<view class="section-header">
				<u-icon name="account" size="36" color="#007AFF" />
				<text class="section-title">客户信息</text>
			</view>

			<view class="info-grid">
				<view class="info-item">
					<text class="label">客户姓名</text>
					<text class="value">{{ customDetails.customerName || '——' }}</text>
				</view>
				<view class="info-item">
					<text class="label">联系电话</text>
					<text class="value">{{ customDetails.customerPhone || '——' }}</text>
				</view>
				<view class="info-item full">
					<text class="label">联系地址</text>
					<text class="value">{{ customDetails.contactAddress || '——' }}</text>
				</view>
				<view class="info-item">
					<text class="label">历史订单数</text>
					<u-tag size="mini" type="success" :text="String(customDetails.orderCount || 0)" shape="circle" />
				</view>
			</view>
		</view>

		<!-- 当前业务员 -->
		<view class="section current-salesman">
			<view class="section-header">
				<u-icon :name="hasOldSalesman ? 'staff' : 'warning'" size="36" :color="hasOldSalesman ? '#409eff' : '#e6a23c'" />
				<text class="section-title" :style="{ color: hasOldSalesman ? '#1a1a1a' : '#e6a23c' }">
					{{ hasOldSalesman ? '当前绑定业务员' : '当前状态：未绑定' }}
				</text>
			</view>
			<template v-if="hasOldSalesman">
				<view class="salesman-card">
					<u-avatar :src="customDetails.salesman?.avatar" :text="customDetails.salesman?.salesmanName?.charAt(0)" size="80" mode="aspectFill" />
					<view class="details">
						<text class="name">{{ customDetails.salesman?.salesmanName }}</text>
						<view class="meta">
							<text>电话：{{ customDetails.salesman?.salesmanPhone || '未填写' }}</text>
							<text>部门：{{ customDetails.salesman?.dept.deptName || '未分配' }}</text>
						</view>
					</view>
				</view>
			</template>

			<template v-else>
				<view class="empty-state">
					<u-icon name="volume-down" size="40" color="#e6a23c" />
					<text class="empty-text">该客户尚未绑定任何业务员</text>
				</view>
			</template>
		</view>
		<!-- 选择新业务员 -->
		<view class="section select-salesman select-boxsection">
			<view class="section-header">
				<u-icon name="man-add" size="36" color="#FFAB00" />
				<text class="section-title">选择新业务员</text>
			</view>
			<view class="salesman-list">
				<view
					v-for="item in salesmanList"
					:key="item.userId"
					class="salesman-card-pro"
					:class="{ active: selectedSalesmanId === item.userId }"
					@click="onSelectChange(item.userId)"
				>
					<view class="left">
						<u-avatar :src="item.avatar" :text="item.nickName?.charAt(0)" size="90" mode="aspectFill" />
					</view>

					<view class="middle">
						<view class="accountBox">
							<text class="name">{{ item.nickName }}</text>
							<text class="dept">{{ item.dept?.deptName || '未分组' }}</text>
						</view>
						<text class="phone">📞 {{ item.userName }}</text>
					</view>

					<view class="right">
						<u-icon v-if="selectedSalesmanId === item.userId" name="checkmark-circle-fill" size="50" color="#007AFF" />
					</view>
				</view>

				<u-empty v-if="salesmanList.length === 0 && !loading" text="暂无业务员" />
				<u-loading-icon v-if="loading" text="加载中..." textSize="14" />
			</view>
		</view>

		<!-- 更换提示 -->
		<view v-if="showChangeTip" class="tip-box">
			<u-alert type="info" :show-icon="true" :title="changeTipText" closable @close="showChangeTip = false" />
		</view>

		<!-- 固定底部操作栏 -->
		<view class="footer-bar">
			<u-button class="submit-btn" type="primary" :loading="submitting" :disabled="!selectedSalesmanId" @click="handleSubmit">确认更换</u-button>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { navBack, setLoadingToast, setToast } from '@/common/utils';
import { getCustomer, updateCustomerSalesman } from '@/api/customers';
import { useYw } from '@/hooks/useYw';

interface SalesmanItem {
	userId: string;
	nickName: string;
	userName: string;
	avatar?: string;
	region?: string;
	dept?: Record<string, any>;
}

interface CustomDetails {
	customerId?: string;
	customerName?: string;
	customerPhone?: string;
	contactAddress?: string;
	orderCount?: number;
	salesman?: {
		salesmanId?: string;
		salesmanName?: string;
		salesmanPhone?: string;
		avatar?: string;
		dept?: Record<string, any>;
	};
}

const { ywList: salesmanList } = useYw();
const customDetails = ref<CustomDetails>({});
const loading = ref(false);
const submitting = ref(false);
const selectedSalesmanId = ref<string | null>(null);

onLoad((query: any) => {
	try {
		getCustomer(query.id).then((res) => {
			if (res.code == 200) {
				const customer = res.data;
				customDetails.value = customer;
				if (customer?.salesman) {
					selectedSalesmanId.value = customer.salesman.salesmanId || null;
				}
			}
		});
	} catch (err) {
		setToast('参数解析失败');
		navBack();
	}
});

const hasOldSalesman = computed(() => !!customDetails.value.salesman?.salesmanId);

const selectedSalesman = computed(() => salesmanList.value.find((item) => item.userId === selectedSalesmanId.value));

const showChangeTip = computed(() => {
	return selectedSalesmanId.value && (!customDetails.value.salesman?.salesmanId || selectedSalesmanId.value !== customDetails.value.salesman?.salesmanId);
});

const changeTipText = computed(() => {
	const oldName = customDetails.value.salesman?.salesmanName || '无';
	const newName = selectedSalesman.value?.nickName || '未知';
	return `即将把客户「${customDetails.value.customerName}」的业务员从「${oldName}」更换为「${newName}」`;
});

const onSelectChange = (val: string) => {
	selectedSalesmanId.value = val;
};

const handleSubmit = () => {
	if (!selectedSalesmanId.value || submitting.value) return;
	const oldName = customDetails.value.salesman?.salesmanName || '无';
	const newName = selectedSalesman.value?.nickName || '未知';

	uni.showModal({
		title: '确认更换？',
		content: `确定将客户「${customDetails.value.customerName}」的业务员从「${oldName}」更换为「${newName}」吗？更换后该客户的所有订单将全部划为「${newName}」下。`,
		confirmColor: '#007AFF',
		success: (res) => {
			if (res.confirm) {
				submitting.value = true;
				setLoadingToast('分配中...');
				updateCustomerSalesman({
					customerId: customDetails.value.customerId,
					salesmanId: selectedSalesmanId.value
				})
					.then((resData) => {
						if (resData.code === 200) {
							uni.showToast({ title: '更换成功', icon: 'success' });
							setTimeout(() => {
								navBack();
							}, 800);
						} else {
							uni.showToast({ title: resData.msg || '操作失败', icon: 'none' });
						}
					})
					.catch(() => {
						uni.showToast({ title: '提交失败', icon: 'none' });
					})
					.finally(() => {
						submitting.value = false;
					});
			}
		}
	});
};
</script>

<style lang="scss" scoped>
.page-container {
	height: 100vh;
	background-color: #f8f9fc;
	display: flex;
	flex-direction: column;
}

.section {
	background: #fff;
	border-radius: 24rpx;
	padding: 32rpx;
	margin-bottom: 24rpx;
	box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.04);
}

.select-boxsection {
	flex: 1;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	margin-bottom: 0;
	padding-bottom: 0;

	.salesman-list {
		flex: 1;
		padding: 10rpx;
		overflow: scroll;
	}
}

.section-header {
	display: flex;
	align-items: center;
	margin-bottom: 28rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #1a1a1a;
	margin-left: 16rpx;
}

.info-grid {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 24rpx;
}

.info-item {
	font-size: 28rpx;
}

.info-item.full {
	grid-column: span 2;
}

.label {
	display: block;
	font-size: 26rpx;
	color: #666;
	margin-bottom: 6rpx;
	font-weight: 500;
}

.value {
	color: #1a1a1a;
	font-size: 28rpx;
}

/* 业务员卡片 */
.salesman-card {
	display: flex;
	align-items: center;
	gap: 24rpx;
	padding: 24rpx;
	background: linear-gradient(135deg, #f7f9ff 0%, #f0f5ff 100%);
	border-radius: 20rpx;
	border: 1px solid #e0e7ff;
}

.details {
	flex: 1;
}

.name {
	font-weight: 600;
	font-size: 30rpx;
	color: #1a1a1a;
	margin-bottom: 8rpx;
}

.meta {
	display: flex;
	flex-wrap: wrap;
	gap: 16rpx;
	font-size: 24rpx;
	color: #666;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 40rpx 0;
	color: #e6a23c;
	font-size: 28rpx;
	font-weight: 500;
}

.empty-text {
	margin-top: 12rpx;
}

/* 选择区 */
.salesman-list {
	display: flex;
	flex-direction: column;
	gap: 28rpx;
	padding: 10rpx 0;
}

.salesman-card-pro {
	display: flex;
	align-items: center;
	padding: 24rpx;
	border-radius: 28rpx;
	background: linear-gradient(135deg, #ffffff 0%, #f9fbff 100%);
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
	border: 3rpx solid transparent;
	transition: all 0.25s ease;
}

.salesman-card-pro.active {
	border-color: #007aff;
	background: linear-gradient(135deg, #f0f7ff 0%, #e6f0ff 100%);
	box-shadow: 0 12rpx 32rpx rgba(0, 122, 255, 0.2);
}

.salesman-card-pro .left {
	margin-right: 28rpx;
}

.salesman-card-pro {
	.middle {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 10rpx;

		.accountBox {
			display: flex;
			align-items: center;

			.name {
				font-size: 34rpx;
				font-weight: 700;
				color: #1a1a1a;
			}
			.dept {
				font-size: 26rpx;
				color: #999;
				margin-left: 15rpx;
			}
		}
	}

	.phone {
		font-size: 28rpx;
		color: #666;
	}

	.right {
		margin-left: 16rpx;
	}
}

/* 提示 */
.tip-box {
	margin: 16rpx 0;
}

/* 底部按钮 */
.footer-bar {
	padding: 20rpx 30rpx;
	background: #fff;
	border-top: 1px solid #eee;
}

.submit-btn {
	border-radius: 12rpx;
	font-weight: 500;
	font-size: 30rpx;
	height: 80rpx;
}
</style>
